#!/usr/bin/perl
#################################################################
# hg_add_copyright.pl -- add highgo copyright throughout the source tree.
#
# Copyright (c) 2019, HighGo Software Inc
#
# src/tools/hgchange/hg_add_copyright.pl
#
#################################################################

use strict;
use warnings;

use File::Find;
use File::Basename;
use Tie::File;

my $pgdg      = 'PostgreSQL Global Development Group';
my $hgdg      = 'HighGo Software Inc';
my $cc        = 'Copyright \(c\)';
my $ccliteral = 'Copyright (c)';
my $b_pcc = 'Portions Copyright (c) 2018-';
my $b_cc = 'Copyright (c) 2018-';
# year-1900 is what localtime(time) puts in element 5
my $year = 1900 + ${ [ localtime(time) ] }[5];
# Use to calculate the time we exec the script
my $time1;
my $time2;
my $time3;

#print "Using current year:  $year\n";
$time1 = time();
find({ wanted => \&wanted, no_chdir => 1 }, '.');

sub wanted
{
	# count current line index
	my $countline = 0;
	# index of pg gdg copyright string
	my $pgdg_location = 0;
	# Assign hg copyright if it find one
	my $hgdg_location = 0;
	my $line_hg = 0;
	my $line_change = 0;
	# prevent corruption of git indexes by ignoring any .git/
	if (basename($_) eq '.git')
	{
		$File::Find::prune = 1;
		return;
	}

	return if !-f $File::Find::name || -l $File::Find::name;

	# skip file names with binary extensions
	return if ($_ =~ m/\.(ico|bin|po)$/);
	return if ($_ =~ m/.*COPYRIGHT$/);
	#print "Search file $_\n";
	my @lines;
	tie @lines, "Tie::File", $File::Find::name;

	foreach my $line (@lines)
	{
		if($line =~ m/$cc.*$hgdg/i)
		{
			# Assign hg copyright index here
			$hgdg_location = $countline;
		}
		$countline = $countline + 1;
		# We only care about lines with a copyright notice.
		next unless $line =~ m/$cc.*$pgdg/i;

		$pgdg_location = $countline - 1;

		# If it has a hg copyright already, then next line.
		next if($pgdg_location - 1 == $hgdg_location);

		# $line_hg is the line we will add.
		$line_hg = $line;
		if($line_hg =~ m/Portions/i)
		{
			$line_hg =~ s/$cc.*$pgdg/$b_cc$year, $hgdg/i;
		}
		else
		{
			$line_hg =~ s/$cc.*$pgdg/$b_pcc$year, $hgdg/i;
		}
		$line_change = $lines[$pgdg_location];
		# Here we combine the new line and fill into the @lines list
		$lines[$pgdg_location] = "$line_hg\n$line_change";
		$hgdg_location = 0;
		$pgdg_location = 0;
	}
	untie @lines;
	return;
}
$time2 = time();
$time3 = $time2 - $time1;
print("Cost time:$time3 seconds\n");
